import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:ls_work/a_message/models/message_row_entity.dart';
import 'package:ls_work/a_message/models/message_section_entity.dart';
import 'package:ls_work/a_message/views/message_row_view.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/util/toast.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';

class MessageRowPage extends StatefulWidget {
  final MessageSectionInfo? info;
  MessageRowPage({Key? key, this.info});
  @override
  _MessageRowPageState createState() => _MessageRowPageState();
}

class _MessageRowPageState extends State<MessageRowPage>
    with AutomaticKeepAliveClientMixin<MessageRowPage> {
  @override
  bool get wantKeepAlive => true;

  int _page = 1;
  List<MessageRowInfo> dataList = [];
  EasyRefreshController _controller = EasyRefreshController();

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _messageRowList();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: Colours.bg_color,
      appBar: AppBar(
        title: Text('${widget.info?.name??""}'),
        elevation: 0.5,
      ),
      body: EasyRefresh(
          header: MaterialHeader(),
          footer: MaterialFooter(),
          enableControlFinishLoad: true,
          onRefresh: _onRefresh,
          onLoad: _loadMore,
          controller: _controller,
          child: ListView.builder(
            itemCount: dataList.length,
            itemBuilder: (context, index) {
              return MessagerowView(
                info: dataList[index],
              );
            },
          )),
    );
  }

  Future _onRefresh() async {
    _page = 1;
    await await _messageRowList();
  }

  Future _loadMore() async {
    _page++;
    await _messageRowList();
  }

  ///城市机构详情信息
  _messageRowList() async {
    var map = {"rows": 10, 'groupId': widget.info?.id};
    if (_page > 1) map['page'] = _page;

    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance.getDio().post(HttpApi.messageRowUrl, data: map).then((r) {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          MessageRowEntity model = MessageRowEntity.fromJson(map['data']);
          var tempArr = model.rows;
          setState(() {
            if (_page == 1) {
              dataList = [];
              dataList = model.rows??[];
            } else {
              dataList += (tempArr??[]);
            }
            _controller.finishLoad(
                success: true, noMore: (model.rows??[]).length != 10);
          });
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print('🦊' + e.toString());
      Toast.show(getErrorMessage(e));
    });
  }
}
